package com.sj.hh.ui.phonecontact;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.mbt.deal.util.ToastUtil;
import com.sj.friendcircle.common.router.RouterList;
import com.sj.hh.R;
import com.sj.hh.ui.phonecontact.fragment.RegisteredFragment;
import com.sj.hh.ui.phonecontact.fragment.UnRegisteredFragment;
import com.sj.hh.util.LocalJsonUtil;
import com.sj.hh.util.SendSMSUtil;
import com.sj.hh.widget.contact.CharacterParser;
import com.sj.hh.widget.contact.entity.SortModel;
import com.sj.hh.widget.contact.entity.SortToken;
import com.vise.xsnow.permission.OnPermissionCallback;
import com.vise.xsnow.permission.PermissionManager;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.rongcloud.im.SealConst;
import cn.rongcloud.im.server.network.http.HttpException;
import cn.rongcloud.im.server.response.BaseResponse;
import cn.rongcloud.im.server.response.FriendInvitationResponse;
import cn.rongcloud.im.server.response.PhoneContactResponse;
import cn.rongcloud.im.server.utils.CommonUtils;
import cn.rongcloud.im.server.utils.NToast;
import cn.rongcloud.im.server.widget.DialogWithYesOrNoUtils;
import cn.rongcloud.im.server.widget.LoadDialog;
import cn.rongcloud.im.ui.activity.base.BaseActivity;

/**
 * 手机联系人
 */
@Route(path = RouterList.PhoneContactActivity.path)
public class PhoneContactActivity extends BaseActivity implements RegisteredFragment.OnFragmentInteractionListener, UnRegisteredFragment.OnFragmentInteractionListener {

    private static final int LINK_MAN = 1;
    private static final int SEND_INVITE_USER = 2;
    private static final int ADD_FRIEND = 3;

    @BindView(R.id.rb_registered_top)
    RadioButton rbRegisteredTop;
    @BindView(R.id.rb_unregistered_top)
    RadioButton rbUnregisteredTop;
    @BindView(R.id.radioGroup_top)
    RadioGroup radioGroupTop;
    @BindView(R.id.ll_top)
    LinearLayout llTop;
    @BindView(R.id.view_pager)
    ViewPager viewPager;

    private List<Fragment> mFragmentList;
    private CharacterParser characterParser;
    private ArrayList<SortModel> mAllContactsList;
    private String phone;
    private String phones;
    private String mFriendId;
    private String addFriendMessage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_phone_contact);
        ButterKnife.bind(this);

        setTitle("手机联系人");
        rbRegisteredTop.setChecked(true);
        //实例化汉字转拼音类
        characterParser = CharacterParser.getInstance();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            PermissionManager.instance().with((Activity) mContext).request(new OnPermissionCallback() {
                @Override
                public void onRequestAllow(String permissionName) {
                    loadContacts();
                }

                @Override
                public void onRequestRefuse(String permissionName) {
                    Toast.makeText(mContext, "权限申请被拒绝，请重试！", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onRequestNoAsk(String permissionName) {
                    Toast.makeText(mContext, "权限申请被拒绝且不再询问，请进入设置打开权限再试！", Toast.LENGTH_SHORT).show();
                }
            }, Manifest.permission.READ_CONTACTS);
        } else {
            loadContacts();
        }

    }

    private void initViewPager() {
        RegisteredFragment registeredFragment = RegisteredFragment.newInstance("", "");
        UnRegisteredFragment unRegisteredFragment = UnRegisteredFragment.newInstance("", "");
        mFragmentList = new ArrayList<Fragment>();
        mFragmentList.add(registeredFragment);
        mFragmentList.add(unRegisteredFragment);
//        if (unRegisteredFragment.isAdded()) {
//            getSupportFragmentManager().beginTransaction().show(unRegisteredFragment).commit();
//        } else {
//            getSupportFragmentManager().beginTransaction().remove(unRegisteredFragment).commit();
//            frament = new Fragment();
//            getSupportFragmentManager().beginTransaction().add(R.id.layout_frame, fragment).commit();
//        }

        viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return mFragmentList.get(position);
            }

            @Override
            public int getCount() {
                return mFragmentList.size();
            }
        });

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
//                mTabHost.setCurrentTab(position);
                if (position == 0) {
                    rbRegisteredTop.setChecked(true);
                    rbUnregisteredTop.setChecked(false);
                } else if (position == 1) {
                    rbUnregisteredTop.setChecked(true);
                    rbRegisteredTop.setChecked(false);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        LoadDialog.dismiss(mContext);
    }

    @OnClick({R.id.rb_registered_top, R.id.rb_unregistered_top})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rb_registered_top:
                if (viewPager != null)
                    viewPager.setCurrentItem(0);
                break;
            case R.id.rb_unregistered_top:
                if (viewPager != null)
                    viewPager.setCurrentItem(1);
                break;
        }
    }

    private void loadContacts() {
        LoadDialog.show(mContext, "正在读取联系人信息...");
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    ContentResolver resolver = getApplicationContext().getContentResolver();
                    Cursor phoneCursor = resolver.query(Phone.CONTENT_URI,
                            new String[]{Phone.DISPLAY_NAME,
                                    Phone.NUMBER,
                                    "sort_key"}, null, null, "sort_key COLLATE LOCALIZED ASC");
                    if (phoneCursor == null || phoneCursor.getCount() == 0) {
                        ToastUtil.makeToast(getApplicationContext(), "未获得读取联系人权限 或 未获得联系人数据");
                        return;
                    }
                    int PHONES_NUMBER_INDEX = phoneCursor.getColumnIndex(Phone.NUMBER);
                    int PHONES_DISPLAY_NAME_INDEX = phoneCursor.getColumnIndex(Phone.DISPLAY_NAME);
                    int SORT_KEY_INDEX = phoneCursor.getColumnIndex("sort_key");
                    if (phoneCursor.getCount() > 0) {
                        mAllContactsList = new ArrayList<SortModel>();
                        while (phoneCursor.moveToNext()) {
                            String phoneNumber = phoneCursor.getString(PHONES_NUMBER_INDEX);
                            if (TextUtils.isEmpty(phoneNumber))
                                continue;
                            String contactName = phoneCursor.getString(PHONES_DISPLAY_NAME_INDEX);
                            String sortKey = phoneCursor.getString(SORT_KEY_INDEX);
                            //System.out.println(sortKey);
                            SortModel sortModel = new SortModel(contactName, phoneNumber, sortKey);
                            //优先使用系统sortkey取,取不到再使用工具取
                            String sortLetters = getSortLetterBySortKey(sortKey);
                            if (sortLetters == null) {
                                sortLetters = getSortLetter(contactName);
                            }
                            sortModel.sortLetters = sortLetters;

                            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
                                sortModel.sortToken = parseSortKey(sortKey);
                            else
                                sortModel.sortToken = parseSortKeyLollipop(sortKey);

                            mAllContactsList.add(sortModel);
                        }
                    }
                    phoneCursor.close();
                    StringBuilder builder = new StringBuilder();
                    for (SortModel sort : mAllContactsList) {
                        builder.append(sort.simpleNumber);
                        builder.append(",");
                    }
                    phones = builder.toString();
                    runOnUiThread(new Runnable() {
                        public void run() {
                            Log.i("xbc", mAllContactsList.toString());
                            LocalJsonUtil.getInstance().setSortModel(mContext, mAllContactsList);
                            request(LINK_MAN);
//                            Collections.sort(mAllContactsList, pinyinComparator);
//                            adapter.updateListView(mAllContactsList);
                        }
                    });
                } catch (Exception e) {
                    Log.e("xbc", e.getLocalizedMessage());
                }
            }
        }).start();
    }

    /**
     * 名字转拼音,取首字母
     *
     * @param name
     * @return
     */
    private String getSortLetter(String name) {
        String letter = "#";
        if (name == null) {
            return letter;
        }
        //汉字转换成拼音
        String pinyin = characterParser.getSelling(name);
        String sortString = pinyin.substring(0, 1).toUpperCase(Locale.CHINESE);

        // 正则表达式，判断首字母是否是英文字母
        if (sortString.matches("[A-Z]")) {
            letter = sortString.toUpperCase(Locale.CHINESE);
        }
        return letter;
    }

    /**
     * 取sort_key的首字母
     *
     * @param sortKey
     * @return
     */
    private String getSortLetterBySortKey(String sortKey) {
        if (sortKey == null || "".equals(sortKey.trim())) {
            return null;
        }
        String letter = "#";
        //汉字转换成拼音
        String sortString = sortKey.trim().substring(0, 1).toUpperCase(Locale.CHINESE);
        // 正则表达式，判断首字母是否是英文字母
        if (sortString.matches("[A-Z]")) {
            letter = sortString.toUpperCase(Locale.CHINESE);
        } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {// 5.0以上需要判断汉字
            if (sortString.matches("^[\u4E00-\u9FFF]+$"))// 正则表达式，判断是否为汉字
                letter = getSortLetter(sortString.toUpperCase(Locale.CHINESE));
        }
        return letter;
    }

    /**
     * 中文字符串匹配
     */
    String chReg = "[\\u4E00-\\u9FA5]+";

    //String chReg="[^\\u4E00-\\u9FA5]";//除中文外的字符匹配

    /**
     * 解析sort_key,封装简拼,全拼
     *
     * @param sortKey
     * @return
     */
    public SortToken parseSortKey(String sortKey) {
        SortToken token = new SortToken();
        if (sortKey != null && sortKey.length() > 0) {
            //其中包含的中文字符
            String[] enStrs = sortKey.replace(" ", "").split(chReg);
            for (int i = 0, length = enStrs.length; i < length; i++) {
                if (enStrs[i].length() > 0) {
                    //拼接简拼
                    token.simpleSpell += enStrs[i].charAt(0);
                    token.wholeSpell += enStrs[i];
                }
            }
        }
        return token;
    }

    /**
     * 解析sort_key,封装简拼,全拼。
     * Android 5.0 以上使用
     *
     * @param sortKey
     * @return
     */
    public SortToken parseSortKeyLollipop(String sortKey) {
        SortToken token = new SortToken();
        if (sortKey != null && sortKey.length() > 0) {
            boolean isChinese = sortKey.matches(chReg);
            // 分割条件：中文不分割，英文以大写和空格分割
            String regularExpression = isChinese ? "" : "(?=[A-Z])|\\s";

            String[] enStrs = sortKey.split(regularExpression);

            for (int i = 0, length = enStrs.length; i < length; i++)
                if (enStrs[i].length() > 0) {
                    //拼接简拼
                    token.simpleSpell += getSortLetter(String.valueOf(enStrs[i].charAt(0)));
                    token.wholeSpell += characterParser.getSelling(enStrs[i]);
                }
        }
        return token;
    }

    @Override
    public void onFragmentInteraction(@Nullable SortModel sortModel) {

        phone = sortModel.simpleNumber;
        if (!TextUtils.isEmpty(phone) && phone.contains(" "))
            phone.replace(" ", "");
        request(SEND_INVITE_USER);
    }

    @Override
    public void onFragmentInteraction(PhoneContactResponse.DataBean dataBean) {
        mFriendId = dataBean.getId() + "";
        DialogWithYesOrNoUtils.getInstance().showEditDialog(mContext, getString(com.mbt.im.R.string.add_text), getString(com.mbt.im.R.string.add_friend), new DialogWithYesOrNoUtils.DialogCallBack() {
            @Override
            public void executeEvent() {

            }

            @Override
            public void updatePassword(String oldPassword, String newPassword) {

            }

            @Override
            public void executeEditEvent(String editText) {
                if (!CommonUtils.isNetworkConnected(mContext)) {
                    NToast.shortToast(mContext, com.mbt.im.R.string.network_not_available);
                    return;
                }
                addFriendMessage = editText;
                if (TextUtils.isEmpty(editText)) {
                    addFriendMessage = "我是" + getSharedPreferences("config", MODE_PRIVATE).getString(SealConst.SEALTALK_LOGIN_NAME, "");
                }
                if (!TextUtils.isEmpty(mFriendId)) {
                    LoadDialog.show(mContext);
                    request(ADD_FRIEND);
                } else {
                    NToast.shortToast(mContext, "id is null");
                }
            }
        });
    }

    @Override
    public Object doInBackground(int requestCode, String id) throws HttpException {
        switch (requestCode) {
            case LINK_MAN:
                return action.linkman(phones);
            case SEND_INVITE_USER:
                return action.sendInviteUser(phone);
            case ADD_FRIEND:
                return action.sendFriendInvitation(mFriendId, addFriendMessage);
        }
        return super.doInBackground(requestCode, id);
    }

    @Override
    public void onSuccess(int requestCode, Object result) {
        if (result != null) {
            switch (requestCode) {
                case SEND_INVITE_USER:
                    BaseResponse baseResponse = (BaseResponse) result;
                    if (baseResponse.getResultCode() == 0) {
                        sendSMS(mContext, phone);
                    } else {
                        NToast.shortToast(mContext, baseResponse.getMsg());
                    }
                    break;
                case LINK_MAN:
                    PhoneContactResponse scrres = (PhoneContactResponse) result;
                    if (scrres.getResultCode() == 0) {
                        List<PhoneContactResponse.DataBean> data = scrres.getData();
                        LocalJsonUtil.getInstance().setPhoneContact(mContext, data);
//                        for (MachineFragment fragment : adapter.getmFragments()) {
//                            fragment.setData(data);
//                        }
                    } else {
                        NToast.shortToast(mContext, scrres.getMsg());
                    }
                    initViewPager();
                    break;
                case ADD_FRIEND:
                    FriendInvitationResponse fres = (FriendInvitationResponse) result;
                    if (fres.getResultCode() == 0) {
                        NToast.shortToast(mContext, fres.getMsg());
//                        NToast.shortToast(mContext, getString(R.string.request_success));
                        LoadDialog.dismiss(mContext);
                    } else {
                        NToast.shortToast(mContext, "请求失败 错误码:" + fres.getCode());
                        LoadDialog.dismiss(mContext);
                    }
                    break;
            }
        }
    }

    @Override
    public void onFailure(int requestCode, int state, Object result) {
        switch (requestCode) {
            case ADD_FRIEND:
                NToast.shortToast(mContext, "你们已经是好友");
                LoadDialog.dismiss(mContext);
                break;
            default:
                LoadDialog.dismiss(mContext);
                NToast.shortToast(mContext, "请求失败！");
                break;
        }
    }

    /**
     * 发送短信
     *
     * @param mContext
     * @param phone
     */
    private void sendSMS(final Context mContext, final String phone) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            PermissionManager.instance().with((Activity) mContext).request(new OnPermissionCallback() {
                @Override
                public void onRequestAllow(String permissionName) {
                    SendSMSUtil.getInstance().doSendSMSTo(mContext, phone, SendSMSUtil.SMS_MODE);
                }

                @Override
                public void onRequestRefuse(String permissionName) {
                    Toast.makeText(mContext, "权限申请被拒绝，请重试！", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onRequestNoAsk(String permissionName) {
                    Toast.makeText(mContext, "权限申请被拒绝且不再询问，请进入设置打开权限再试！", Toast.LENGTH_SHORT).show();
                }
            }, Manifest.permission.SEND_SMS);
        } else {
            SendSMSUtil.getInstance().doSendSMSTo(mContext, phone, SendSMSUtil.SMS_MODE);
        }
    }

}
